<?php

namespace App\Livewire;

use App\Models\Chapter;
use App\Service\BqsService;
use Livewire\Attributes\Computed;
use Livewire\Component;

class ChapterPage extends Component
{
    public Chapter $chapter;

    public string $content = '';
    public function mount(Chapter $chapter)
    {
        if (!$chapter->chapter_content) {
            $res =  BqsService::getReadInfo($chapter->chapter_link);
            $res &&  $chapter->chapter_content = $res['text'];
            $chapter->save();
            $chapter->refresh();
        }
        $this->chapter = $chapter;

    }
    public function render()
    {
        return view('livewire.chapter-page')->layoutData([
            'category' => $this->chapter?->book?->category,
        ]);
    }

    #[Computed]
    public function preChapter()
    {
        return Chapter::where('id', '<', $this->chapter->id)->where('book_id', $this->chapter->book_id)->orderBy('id', 'desc')->first();
    }

    #[Computed]
    public function nextChapter()
    {
        return Chapter::where('id', '>', $this->chapter->id)->where('book_id', $this->chapter->book_id)->orderBy('id', 'asc')->first();
    }
}
